package mymyoux.io.sockets.servers.mserverClasses
{
	import flash.utils.ByteArray;
	
	import mymyoux.io.sockets.clients.BinarySocket;
	import mymyoux.io.sockets.mapping.Telegramme;
	import mymyoux.signals.Signal;

	public class SBinarySocket
	{
		private var _socket:BinarySocket;
		private var _signalData:Signal;
		private var _signalStatus:Signal;
		public function SBinarySocket(socket:BinarySocket = null)
		{
			_signalData = new Signal(Telegramme);
			_signalStatus = new Signal(Boolean);
			this.socket = socket;
		}
		public function get signalData():Signal
		{
			return _signalData;
		}
		public function get signalStatus():Signal
		{
			return _signalStatus;
		}
		public function get socket():BinarySocket
		{
			return _socket;
		}

		public function set socket(value:BinarySocket):void
		{
			_socket = value;
			_socket.signalStatus.add(onStatus);
			_socket.signalData.add(onData);
		}
		private function onStatus(socket:BinarySocket, connected:Boolean):void
		{
			_signalStatus.dispatch(connected);
		}
		private function onData(socket:BinarySocket, value:ByteArray):void
		{
			var telegramme:Telegramme;
			while(value.bytesAvailable > 0)
			{
				try
				{
					telegramme = value.readObject() as Telegramme;
					
				}catch(error:Error)
				{
					trace("SERVER_ERROR_READING:["+error+"]");
					//if we are here, value is malformed
					break;
				}
				_signalData.dispatch(telegramme);
			}
		}
		public function write(telegramme:Telegramme):void
		{
			socket.write(telegramme);
		}

	}
}